package cn.com.bluemoon.daps.model.controller.api;

import cn.com.bluemoon.daps.api.model.RemoteDataModelTableService;
import cn.com.bluemoon.daps.common.constant.ServiceNameConstants.DapsApiModel;
import cn.com.bluemoon.daps.common.datascope.BmPermission;
import cn.com.bluemoon.daps.common.domain.ResultBean;
import cn.com.bluemoon.daps.common.enums.BmStatus;
import cn.com.bluemoon.daps.common.toolkit.BmAssetUtils;
import cn.com.bluemoon.daps.model.dto.DapDataModelTableDto;
import cn.com.bluemoon.daps.model.entity.DapDataModelTable;
import cn.com.bluemoon.daps.model.mapper.DapDataModelTableMapper;
import cn.com.bluemoon.daps.model.service.DapDataModelTableService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@Api(tags = {"FeignClient服务-模型-table-api接口"})
@RequestMapping(DapsApiModel.API_MODEL_TABLE)
@BmPermission(value = "", name = "服务注册-模型表", ignore = true)
@RestController
@Slf4j
public class DapDataModelTableServiceApi implements RemoteDataModelTableService {

    @Resource
    DapDataModelTableService tableService;

    @PostMapping("/list")
    public List<DapDataModelTableDto> getTablePublishInfos(@RequestParam("modelId") String modelId, @RequestParam("isPublish") int isPublish) {
        return tableService.getBaseMapper(DapDataModelTableMapper.class).getTablePublishInfos(modelId, isPublish);
    }

    @PostMapping("/updateTable")
    @ApiOperation(("根据id表信息"))
    public ResultBean<Boolean> updateById(@RequestParam("tableId") String id,
                                          @RequestBody DapDataModelTable newTable) {
        LambdaUpdateWrapper<DapDataModelTable> updateWrapper = tableService.bmLambdaUpdate()
                .set(DapDataModelTable::getEngName, newTable.getEngName())
                .set(DapDataModelTable::getName, newTable.getName())
                .eq(DapDataModelTable::getId, id);
        boolean update = tableService.update(updateWrapper);
        log.info("更新表{}", id);
        return ResultBean.ok(update);
    }

    @DeleteMapping("/deleteTable")
    @ApiOperation(("根据id表信息"))
    public ResultBean<Boolean> removeById(@RequestParam("tableId") String id) {
        boolean remove = tableService.removeById(id);
        return ResultBean.ok(remove);
    }

    @PostMapping("/saveTable")
    @ApiOperation(("根据id表信息"))
    public ResultBean<String> saveTable(@RequestBody DapDataModelTable newTable) {
        // 2021/8/9 重建表：保存返回表id，getRenewTable返回的id可能表中已存在！！只能用saveOrUpdate
        newTable.setId(tableService.getRenewTable(newTable.getDataModelId(), newTable.getEngName()));
        boolean save = tableService.saveOrUpdate(newTable);
        BmAssetUtils.isTrue(save, "新增表信息失败");
        return ResultBean.ok(newTable.getId());
    }

    @GetMapping("/listByModelAndNewst")
    @ApiOperation(("获取模型表列表"))
    public ResultBean<List<DapDataModelTable>> listByModelIdAndNewest(@RequestParam("modelId") String modelId,
                                                                      @RequestParam(value = "newest", defaultValue = "true") boolean newest) {
        List<DapDataModelTable> list = tableService.findAllByPageByModelIdAndNewest(modelId, newest);
        return ResultBean.ok(list);
    }

    @GetMapping("save/updateTime")
    public ResultBean<Boolean> updateTableTime(@RequestParam("modelId") String modelId, @RequestParam("tableId") String tableId) {

        // 刷新表更新时间
        tableService.saveTime(tableId);
        return ResultBean.ok(true);
    }

    @GetMapping("/get/topic/table")
    @ApiOperation(value = "查询主题是否被模型表引用")
    public ResultBean<Boolean> getTopicTable(@RequestParam("topicId") String topicId) {
        List<DapDataModelTable> tables = tableService.getBaseMapper().selectList(new LambdaQueryWrapper<DapDataModelTable>().
                eq(DapDataModelTable::getBmStatus, BmStatus.ON.getCode()).eq(DapDataModelTable::getPId, "0")
                .like(DapDataModelTable::getCategoryId, topicId));
        return ResultBean.ok(tables.isEmpty());
    }

    @PostMapping("/get/table/list")
    @ApiOperation(value = "根据多个id获取表信息")
    public ResultBean<List<DapDataModelTable>> getTableList(@RequestBody List<String> tableIds) {

        return ResultBean.ok(tableService.getBaseMapper().selectBatchIds(tableIds));

    }

    @Override
    public ResultBean<List<String>> findTableInfo(String modelId, String tableName, String fieldName) {
        final DapDataModelTableMapper baseMapper = tableService.getBaseMapper(DapDataModelTableMapper.class);
        List<Map<String, Object>> tableAndFieldId = baseMapper.findTableAndFieldId(modelId, tableName, fieldName);
        if (tableAndFieldId == null || tableAndFieldId.isEmpty()) {
            return ResultBean.ok(Collections.emptyList());
        }
        if (tableAndFieldId.size() >= 2) {
            Optional<Map<String, Object>> version = tableAndFieldId.stream()
                    .filter(t -> t.get("dataNewest").toString().equalsIgnoreCase("0") || !Boolean.parseBoolean(t.get("dataNewest").toString()))
                    .findFirst();
            List<String> res = version.map(m -> Arrays.asList(m.get("tableId").toString(), m.get("fieldId").toString())).orElse(Collections.emptyList());
            return ResultBean.ok(res);
        }
        List<String> ids = Arrays.asList(tableAndFieldId.get(0).get("tableId").toString(), tableAndFieldId.get(0).get("fieldId").toString());
        return ResultBean.ok(ids);
    }


}
